let _Vue = null
export default class VueRouter {
  static install(Vue) {
    // 判断当前插件是否已经安装
    if (VueRouter.install.installed) return
    VueRouter.install.installed = true
    // 把Vue构造函数记录到全局变量
    _Vue = Vue
    // 把创建Vue实例时候传入的router对象注入到Vue实例上
    _Vue.mixin({
      beforeCreate() {
        if (this.$options.router) {
          _Vue.prototype.$router = this.$options.router
          this.$options.router.init()
        }
      }
    })
  }
  constructor(options){
    this.options = options
    this.routeMap = {}
    this.mode = options.mode
    // 创建响应式对象
    this.data = _Vue.observable({
      current: '/'
    })
  }
  init(){
    this.createRouteMap()
    this.initComponents(_Vue)
    this.initEvent()
  }
  createRouteMap() {
    // 遍历所有的路由规则，把路由规则解析成键值对的形式 存储到routerMap中
    this.options.routes.forEach(route => {
      this.routeMap[route.path] = route.component
    })
  }
  initComponents(Vue) {
    const self = this
    Vue.component('router-link',{
      props: {
        to: String
      },
      // template: '<a :href="to"><slot></slot></a>'
      render(h){
        return h('a',{
          attrs: {
            href: self.mode === 'hash' ? `#${this.to}` : this.to
          },
          on: {
            click: this.clickHandler
          }
        },[this.$slots.default])
      },
      methods: {
        clickHandler(e){
          // 改变地址栏，但不能触发请求
          if(self.mode !== 'hash'){
            history.pushState({}, '', this.to)
            e.preventDefault()
          }
          // 找到路由对象
          this.$router.data.current = this.to
          
        }
      }
    })
    Vue.component('router-view',{
      render(h){
        // 获取当前组件
        const component = self.routeMap[self.data.current]
        return h(component)
      }
    })
  }
  initEvent () {
    if(this.mode !== 'hash'){
      window.addEventListener('popstate', () => {
        this.data.current = window.location.pathname
      })
    }else{
      window.addEventListener('load',()=>{
        this.data.current = window.location.hash.slice(1)
        if(!this.data.current){
          this.data.current = '/'
          window.location.hash = '#/'
        }
      })
      window.addEventListener('hashchange',()=>{
        this.data.current = window.location.hash.slice(1)
      })
    }
    
  }
}